<template>
  <div style="background-color: white">
    <!--  头像部分-->
    <div>
      <div class="top">
        <img src="../../assets/img/touxiang.jpeg" alt="头像" class="top-head" />
        <div v-if="user" class="top-name">
          <p style="font-size: 24px; margin-bottom: 15px; font-weight: 700">
            {{ user.username || $t("userorder.username_not_set") }}
          </p>
          <p style="margin-bottom: 5px">
            {{ user.phone || $t("userorder.no_phone_number") }}
          </p>
          <p @click="goToUserLocation" class="top-location">
            <el-icon><Location /></el-icon>
            {{ $t("userorder.shipping_address") }}
          </p>
        </div>
        <div v-else>暂未获取到用户信息，请稍后重试</div>
      </div>
      <!--  四个状态和售后-->
      <div class="top-bottom">
        <div
          style="
            font-size: 24px;
            font-weight: 700;
            height: 28px;
            margin: 0px 0px 12px;
          "
        >
          {{ $t("userorder.my_orders") }}
        </div>
        <ul class="top-order-status">
          <li>
            <a href="#" @click.prevent="goToOrderStatus('unpaid')">
              <span class="order-count">{{ unpaidCount }}</span
              >{{ $t("userorder.unpaid") }}</a
            >
          </li>
          <span class="separator"></span>
          <li>
            <a href="#" @click.prevent="goToOrderStatus('unshipped')">
              <span class="order-count">{{ unshippedCount }}</span
              >{{ $t("userorder.unshipped") }}</a
            >
          </li>
          <span class="separator"></span>
          <li>
            <a href="#" @click.prevent="goToOrderStatus('unreceived')">
              <span class="order-count">{{ unreceivedCount }}</span
              >{{ $t("userorder.unreceived") }}</a
            >
          </li>
          <span class="separator"></span>
          <li>
            <a href="#" @click.prevent="goToOrderStatus('completed')">
              <span class="order-count">{{ completedCount }}</span
              >{{ $t("userorder.refund_after_sales") }}</a
            >
          </li>
        </ul>
      </div>
    </div>

    <!--  我的物流-->
  </div>
</template>

<script setup>
import "../../assets/css/UserOrder.css";
import { ElMessage } from "element-plus";
import request from "@/utils/request.js";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";

const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerid = userInfo.id;

// 定义响应式变量
const user = ref(null);
const isLoading = ref(false);
const router = useRouter();

// 订单数量统计
const unpaidCount = ref(0);
const unshippedCount = ref(0);
const unreceivedCount = ref(0);
const completedCount = ref(0);

//跳转页面
const goToUserLocation = () => {
  router.push({ name: "UserLocation" });
};

// 跳转到对应状态的订单页面
const goToOrderStatus = (status) => {
  router.push({
    path: "myorder", // MyOrder.vue 的路由路径
    query: { status },
  });
};

// 发送请求获取用户信息
const fetchUserData = (userId) => {
  isLoading.value = true;
  request
    .get(`/buyer/selectById/${buyerid}`)
    .then((response) => {
      // 假设返回数据在 response.data 中
      if (response.code === "200") {
        user.value = response.data;
      } else {
        ElMessage.error($t("userorder.fetch_user_info_failed"));
      }
    })
    .catch((error) => {
      console.error("请求出错：", error);
      ElMessage.error($t("userorder.request_error"));
    })
    .finally(() => {
      isLoading.value = false;
    });
};

// 获取订单数据并统计数量
const fetchOrders = () => {
  request
    .get(`/order/apid/${buyerid}`)
    .then((res) => {
      unpaidCount.value = res.filter(
        (order) => order.orderStatus === "UNPAID"
      ).length;
      unshippedCount.value = res.filter(
        (order) =>
          order.orderStatus === "PAID" && order.orderStatus !== "SHIPPED"
      ).length;
      unreceivedCount.value = res.filter(
        (order) =>
          order.orderStatus === "SHIPPED" && order.orderStatus !== "RECEIVED"
      ).length;
      completedCount.value = res.filter(
        (order) => order.orderStatus === "COMPLETED"
      ).length;
    })
    .catch((err) => {
      console.error("获取订单数据失败", err);
      ElMessage({
        message: $t("userorder.fetch_order_data_failed"),
        type: "error",
      });
    });
};

// 页面加载时自动获取用户数据
onMounted(() => {
  fetchUserData();
  fetchOrders();
});
</script>
